package com.hh.utils;


import com.hh.entity.vo.CommentTreeVO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论树构建服务
 * com.hh.utils
 *
 * @author
 * @version 0.0.1
 * @date 2025/7/20
 **/
@Component
public class CommentTreeBuilder {

    /**
     * 构建评论树形结构
     *
     * @param flatList 扁平评论列表
     * @return 树形结构评论列表
     */
    public List<CommentTreeVO> buildTree(List<CommentTreeVO> flatList) {
        // 1. 创建ID到评论的映射
        Map<Long, CommentTreeVO> commentMap = new HashMap<>();
        flatList.forEach(comment -> {
            commentMap.put(comment.getId(), comment);
            // 初始化回复列表
            if (comment.getReplies() == null) {
                comment.setReplies(new ArrayList<>());
            }
        });

        // 2. 构建树形结构
        List<CommentTreeVO> rootComments = new ArrayList<>();

        for (CommentTreeVO comment : flatList) {
            Long parentId = comment.getParentId();

            if (parentId == null || parentId == 0) {
                // 顶级评论
                rootComments.add(comment);
            } else {
                // 子评论
                CommentTreeVO parent = commentMap.get(parentId);
                if (parent != null) {
                    parent.getReplies().add(comment);
                }
            }
        }

        // 3. 对回复按时间排序（可选）
        rootComments.forEach(this::sortReplies);

        return rootComments;
    }

    /**
     * 递归排序评论的回复
     *
     * @param comment 评论
     */
    private void sortReplies(CommentTreeVO comment) {
        if (comment.getReplies() != null && !comment.getReplies().isEmpty()) {
            // 按创建时间倒序排序（最新回复在最前面）
            comment.setReplies(
                    comment.getReplies().stream()
                            .sorted((c1, c2) -> c2.getCreatedTime().compareTo(c1.getCreatedTime()))
                            .collect(Collectors.toList())
            );

            // 递归排序子回复
            comment.getReplies().forEach(this::sortReplies);
        }
    }
}
